import React, {createElement} from "react";
import {BrowserRouter as Router, Route, Switch} from "react-router-dom";
import Loadable from 'react-loadable';
import {Spin} from 'antd';
import routeConfig from './router.config';

const routerData = routeConfig;

const dynamicWrapper = (path) => {
    return Loadable({
        loader: () => {
            return import('../' + path).then(raw => {
                const Component = raw.default || raw;
                return (props) =>
                    createElement(Component, {
                        ...props
                    });
            })
        },
        loading: (res) => {
            if (res.error) throw(res.error)
            return (
                <div className="page-loading-warp">
                    <Spin size="large" className="global-spin"/>
                </div>
            )
        }
    });
}

const toComponent = (data) => {
    data.forEach(item => {
        item.component = dynamicWrapper(item.component)
        if (item.routes) {
            toComponent(item.routes)
        }
    });

}
toComponent(routerData)

const Routes = () => {

    return (
        <Router>
            <Switch>
                {routerData.map((item, index) => (
                    <Route key={index} path={item.path} render={(props) => (
                        <item.component {...props} routes={item.routes}/>
                    )}/>
                ))}
            </Switch>
        </Router>
    );
}

export default Routes;
